from typing import AsyncGenerator, Optional
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.security import verify_token
from app.crud.user import user as user_crud
from app.models.user import User
from app.schemas.token import TokenPayload
from app.utils.redis_client import redis_client
from app.utils.exceptions import (
    AuthenticationException,
    TokenExpiredException,
    TokenBlacklistedException,
    InvalidTokenException,
    UserNotFoundException,
    UserInactiveException,
)

# HTTP Bearer token security
security = HTTPBearer()


async def get_current_user_token(
    credentials: HTTPAuthorizationCredentials = Depends(security),
) -> TokenPayload:
    """
    Validate JWT token and return token payload
    """
    token = credentials.credentials
    
    # Verify token
    payload = verify_token(token)
    if not payload:
        raise InvalidTokenException()
    
    # Check if token is blacklisted
    jti = payload.get("jti")
    if jti and await redis_client.is_token_blacklisted(jti):
        raise TokenBlacklistedException()
    
    # Validate token type
    if payload.get("type") != "access":
        raise InvalidTokenException()
    
    return TokenPayload(**payload)


async def get_current_user(
    db: AsyncSession = Depends(get_db),
    token_payload: TokenPayload = Depends(get_current_user_token),
) -> User:
    """
    Get current authenticated user
    """
    user_id = token_payload.sub
    if not user_id:
        raise InvalidTokenException()
    
    db_user = await user_crud.get(db, id=user_id)
    if not db_user:
        raise UserNotFoundException()
    
    if not user_crud.is_active(db_user):
        raise UserInactiveException()
    
    return db_user


async def get_current_active_superuser(
    current_user: User = Depends(get_current_user),
) -> User:
    """
    Get current authenticated superuser
    """
    if not user_crud.is_superuser(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="The user doesn't have enough privileges"
        )
    return current_user


async def get_refresh_token_payload(
    credentials: HTTPAuthorizationCredentials = Depends(security),
) -> TokenPayload:
    """
    Validate refresh token and return payload
    """
    token = credentials.credentials
    
    # Verify token
    payload = verify_token(token)
    if not payload:
        raise InvalidTokenException()
    
    # Check if token is blacklisted
    jti = payload.get("jti")
    if jti and await redis_client.is_token_blacklisted(jti):
        raise TokenBlacklistedException()
    
    # Validate token type
    if payload.get("type") != "refresh":
        raise InvalidTokenException()
    
    return TokenPayload(**payload)